package it.unipd.fbaron.mind_reader_squared.model;

import it.unipd.fbaron.mind_reader_squared.R;

import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;

public class ProfileLogic {

	// Singleton
	private static ProfileLogic istance;

	// DB Helper
	private DataBaseHelper dbHelper;

	private ProfileLogic(DataBaseHelper dbHelper) {
		this.dbHelper = dbHelper;
	}

	public static ProfileLogic getInstance(DataBaseHelper dbHelper) {
		if (istance == null) {
			istance = new ProfileLogic(dbHelper);
		}
		return istance;
	}

	public ArrayList<ProfileDAO> getProfilesList() {
		Cursor result = dbHelper.getReadableDatabase().rawQuery(
				"SELECT * FROM " + DataBaseHelper.PROFILE_TABLE_NAME, null);

		ArrayList<ProfileDAO> list = new ArrayList<ProfileDAO>();
		while (result.moveToNext()) {
			ProfileDAO p = new ProfileDAO(result.getInt(0),
					result.getString(1), result.getString(2),
					result.getString(3), DataBaseHelper.intToDate(
							result.getInt(4), result.getInt(5),
							result.getInt(6)), result.getString(7),
					result.getInt(8), DataBaseHelper.intToDate(
							result.getInt(9), result.getInt(10),
							result.getInt(11)));
			p.setPreferredLanguage(result.getString(12));
			p.setPreferredTts(result.getString(13));
			p.setRating(result.getInt(14));
			p.setOpenM2(result.getInt(15));
			p.setOpenM3(result.getInt(16));
			p.setReadAll(result.getInt(17));
			p.setVirtualDpad(result.getInt(18));
			p.setInputLeft(result.getInt(19));
			p.setInputRight(result.getInt(20));
			p.setInputSelect(result.getInt(21));
			list.add(p);
		}

		return list;
	}

	public int registerProfile(Context context, ProfileDAO profile) {
		int id = -1;
		Date birthDate = profile.getBirthDate();
		Date registrationDate = profile.getRegistrationDate();

		ContentValues cv = new ContentValues();
		cv.put("password", profile.getPassword());
		cv.put("first_name", profile.getFirstName());
		cv.put("last_name", profile.getLastName());
		cv.put("birth_date_y", birthDate.getYear() - 1900);
		cv.put("birth_date_m", birthDate.getMonth());
		cv.put("birth_date_d", birthDate.getDate());
		cv.put("language", profile.getLanguage());
		cv.put("preferred_mod", profile.getPreferredMod());
		cv.put("registration_date_y", registrationDate.getYear());
		cv.put("registration_date_m", registrationDate.getMonth());
		cv.put("registration_date_d", registrationDate.getDate());
		cv.put("preferred_language", profile.getPreferredLanguage());
		cv.put("preferred_tts", profile.getPreferredTts());
		cv.put("rating", profile.getRating());
		cv.put("open_m2", profile.getOpenM2());
		cv.put("open_m3", profile.getOpenM3());
		cv.put("read_all", profile.getReadAll());
		cv.put("virtual_dpad", profile.getVirtualDpad());
		cv.put("input_left", profile.getInputLeft());
		cv.put("input_right", profile.getInputRight());
		cv.put("input_select", profile.getInputSelect());
		try {
			id = (int) dbHelper.getWritableDatabase().insertOrThrow(
					DataBaseHelper.PROFILE_TABLE_NAME, null, cv);
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}

		TypedArray symbolList = context.getResources().obtainTypedArray(
				R.array.m1_symbol_list);
		TypedArray defaultImages = context.getResources().obtainTypedArray(
				R.array.m1_symbols_default_images);
		TypedArray defaultTexts = context.getResources().obtainTypedArray(
				R.array.m1_symbols_default_texts);

		for (int i = 0; i < symbolList.length(); i++) {
			cv = new ContentValues();
			cv.put("name", symbolList.getString(i));
			cv.put("image_resource",
					defaultImages.getResourceId(i, R.string.m1_text_not_found));
			cv.put("text", DataBaseHelper.cleanStringForSave(context
					.getResources().getString(
							defaultTexts.getResourceId(i,
									R.string.m1_text_not_found))));
			cv.put("image_path", "");
			cv.put("parent", "NULL");
			cv.put("m1", 1);
			cv.put("m1_pos", i);
			cv.put("m2", 1);
			cv.put("m2_pos", i);
			cv.put("sound_path", "");
			cv.put("profile", id);
			cv.put("clicks_m1", 0);
			cv.put("sound_choise", 0);
			cv.put("clicks_m2", 0);
			dbHelper.getWritableDatabase().insert(
					DataBaseHelper.SYMBOL_TABLE_NAME, null, cv);
		}
		symbolList.recycle();
		defaultImages.recycle();
		defaultTexts.recycle();
		return id;
	}

	public boolean login(int id, String password) {
		Cursor result = dbHelper.getReadableDatabase().rawQuery(
				"SELECT password FROM " + DataBaseHelper.PROFILE_TABLE_NAME
						+ " WHERE ID=" + id, null);

		result.moveToFirst();
		if (password.equals(result.getString(0)))
			return true;
		else
			return false;
	}

	public String[] queryWithId(int id, String[] columns) {
		String select = "";
		for (int i = 0; i < columns.length; i++) {
			if (i == 0)
				select = columns[i];
			else
				select = select + "," + columns[i];
		}
		Cursor result = dbHelper.getReadableDatabase()
				.rawQuery(
						"SELECT " + select + " FROM "
								+ DataBaseHelper.PROFILE_TABLE_NAME
								+ " WHERE ID=" + id, null);

		String[] values = new String[columns.length];
		result.moveToFirst();
		for (int i = 0; i < columns.length; i++) {
			values[i] = result.getString(i);
		}

		return values;
	}

	public ProfileDAO loadProfile(int id) {
		Cursor result = dbHelper.getReadableDatabase().rawQuery(
				"SELECT * FROM " + DataBaseHelper.PROFILE_TABLE_NAME
						+ " WHERE ID=" + id, null);

		result.moveToFirst();
		ProfileDAO p = new ProfileDAO(result.getInt(0), result.getString(1),
				result.getString(2), result.getString(3),
				DataBaseHelper.intToDate(result.getInt(4), result.getInt(5),
						result.getInt(6)), result.getString(7),
				result.getInt(8), DataBaseHelper.intToDate(result.getInt(9),
						result.getInt(10), result.getInt(11)));
		p.setPreferredLanguage(result.getString(12));
		p.setPreferredTts(result.getString(13));
		p.setRating(result.getInt(14));
		p.setOpenM2(result.getInt(15));
		p.setOpenM3(result.getInt(16));
		p.setReadAll(result.getInt(17));
		p.setVirtualDpad(result.getInt(18));
		p.setInputLeft(result.getInt(19));
		p.setInputRight(result.getInt(20));
		p.setInputSelect(result.getInt(21));

		return p;
	}

	public void updateProfile(int id, ContentValues cv) {
		try {
			dbHelper.getWritableDatabase().update(
					DataBaseHelper.PROFILE_TABLE_NAME, cv, "ID=" + id, null);
		} catch (SQLiteException e) {
		}
	}
}
